﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DHQGHN.Common;
using DHQGHN.DAL.Common;
using DHQGHN.PM0.Models.Admin;
using DHQGHN.PM0.Controllers;
using DHQGHN.DAL.BO.Admin;
using DHQGHN.PM0.Common.Attributes;
using DHQGHN.MVC.Controllers;

namespace DHQGHN.PM0.Controllers
{
    public class RelationController : BaseController
    {
        public const int REQUEST_ACTIVE = 1;
        log4net.ILog logger = log4net.LogManager.GetLogger(typeof(RelationController));
        public ActionResult Index(RelationModel a = null, int pageIndex = 0, string sort = "Id", string sortDir = "ASC", string currentID = null)
        {
            try
            {
                if (a == null) a = new RelationModel();
                if (string.IsNullOrEmpty(currentID)) currentID = string.Empty;

                ViewBag.ActiveMenus = ViewBag.ActiveMenus == null ? new System.Collections.Hashtable() : ViewBag.ActiveMenus;
                ViewBag.ActiveMenus[13] = "active";
                ViewBag.ActiveMenus[240] = "active";
                var model = search(a, pageIndex, currentID, false);
                return View("~/Views/Relation/Relation.cshtml", model);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        /// Hiển thị form thêm mới quan hệ
        [HttpPost]
        public ActionResult actionPrepareCreateOrUpdateRelation(string id)
        {
            try
            {
                RelationModel model = null;
                if (!String.IsNullOrEmpty(id))
                {
                    RelationBO relationBO = new RelationBO();
                    model = new RelationModel(relationBO.GetRelationById(id));
                }
                if (model == null)
                {
                    model = new RelationModel();
                }
                if (Request.IsAjaxRequest())
                {
                    return PartialView("~/Views/Relation/_RelationModel.cshtml", model);
                }
                return View(model);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        [HttpPost]
        public ActionResult actionSearch(RelationModel aModel = null, int pageIndex = 0, string sort = "Id", string sortDir = "ASC", string currentId = null)
        {
            try
            {
                if (aModel == null) aModel = new RelationModel();
                if (string.IsNullOrEmpty(currentId)) currentId = string.Empty;

                var model = search(aModel, pageIndex, currentId, false);
                return PartialView("~/Views/Relation/_RelationList.cshtml", model);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }
        /// Thêm mới quan hệ
        [HttpPost]
        [ValidateInput(false)]
        [AjaxValidateAntiForgeryToken]
        public ActionResult actionCreateOrUpdateRelation(RelationModel model)
        {
            try
            {
                if (Request.IsAjaxRequest())
                {
                    RelationBO relationBO = new RelationBO();
                    bool result = relationBO.createOrUpdateRelation(model.toDALModel());
                    if (result)
                    {
                        LogStream.Write<RelationModel>(GetCurrentUserName(),
                            CommonData.AppName,
                            GetFunction(),
                            Resources.Localization.ActionSaveUpdateCaption + " - actionCreateOrUpdateRelation", model);

                        if (!(String.IsNullOrEmpty(model.RELATION_ID) || String.IsNullOrWhiteSpace(model.RELATION_ID)))
                        {
                            return Json(JsonResponse.Json200("Cập nhật mối quan hệ thành công!"));
                        }
                        else
                        {
                            return Json(JsonResponse.Json200("Thêm mới mối quan hệ thành công!"));
                        }
                    }
                    else
                    {
                        return Json(JsonResponse.Json500("Xảy ra lỗi trong quá trình xử lý!"));
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
            return null;
        }

        [AjaxValidateAntiForgeryToken]
        public ActionResult actionDelete(string[] id)
        {
            try
            {
                if (Request.IsAjaxRequest())
                {
                    RelationBO relationBO = new RelationBO();
                    bool result = relationBO.deleteRelation(id);
                    if (result)
                    {
                        LogStream.Write(GetCurrentUserName(),
                           CommonData.AppName,
                           GetFunction(),
                           CommonData.GetListId(id),
                           Resources.Localization.ActionDeleteCaption + " - actionDelete");

                        return Json(JsonResponse.Json200("Xóa mối quan hệ thành công!"));
                    }
                    else
                    {
                        return Json(JsonResponse.Json500("Xảy ra lỗi trong quá trình xử lý!"));
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
            return null;
        }

        private DataPage<RelationModel> search(RelationModel aModel, int pageIndex, string currentId, bool compareEqual)
        {
            try
            {
                RelationBO relationBO = new RelationBO();

                var DALModel = relationBO.GetDynamicListPaging(aModel.toDALModel(), PageSize, pageIndex, compareEqual);
                var models = new DataPage<RelationModel>();
                var lstItem = DALModel.Data;
                foreach (DHQGHN.DAL.Models.Admin.RelationModel relation in lstItem)
                {
                    models.Data.Add(new RelationModel(relation));
                }

                RelationModel model = null;
                if (!String.IsNullOrEmpty(currentId) && models.Data.Count > 0)
                {
                    model = models.Data.Find(user => Equals(user.RELATION_ID, currentId));
                    models.CustomData = model;
                }
                else
                {
                    models.CustomData = aModel;
                }
                if (models.Data.Count > 0)
                {
                    //Tao component phan trang
                    var pagNative = new Pagination
                    {
                        ActionName = "actionSearch",
                        ModelName = "Relation",
                        CurrentPage = pageIndex,
                        InputSearchId = string.Empty,
                        TagetReLoadId = "relation-list",

                    };
                    pagNative.TotalRows = models.Data[0].RecordCount;
                    pagNative.CurrentRow = models.Data.Count;
                    ViewBag.Pagination = pagNative;
                }

                return models;
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        //Kiểm tra tên quan hệ đã tồn tại chưa
        public JsonResult CheckExistRelationName(string name, string Relation_Id)
        {
            try
            {
                var isExist = false;
                if (!string.IsNullOrEmpty(name))
                {
                    RelationModel relationModel = new RelationModel()
                    {
                        NAME = name
                    };

                    var model = search(relationModel, 0, string.Empty, true);

                    if (model.Data.Any())
                    {
                        var lstItem = model.Data;
                        foreach (RelationModel relation in lstItem)
                        {
                            if (!(String.IsNullOrEmpty(Relation_Id) || String.IsNullOrWhiteSpace(Relation_Id)))
                            {
                                if (!Equals(relation.RELATION_ID, Relation_Id))
                                {
                                    isExist = true;
                                    break;
                                }
                            }
                            else
                            {
                                //Kiem tra truong hop them moi
                                isExist = true;
                                break;
                            }
                        }
                    }
                }
                if (isExist)
                {
                    return Json(Resources.Localization.RelationNameExist);
                }
                else
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        //Kiểm tra mã quan hệ đã tồn tại chưa
        public JsonResult CheckExistRelationCode(string code, string Relation_Id)
        {
            try
            {
                
                var isExist = false;
                if (!string.IsNullOrEmpty(code))
                {
                    RelationModel relationModel = new RelationModel()
                    {
                        CODE = code
                    };
                    var model = search(relationModel, 0, string.Empty, true);

                    if (model.Data.Any())
                    {


                        var lstItem = model.Data;
                        foreach (RelationModel relation in lstItem)
                        {
                            if (!(String.IsNullOrEmpty(Relation_Id) || String.IsNullOrWhiteSpace(Relation_Id)))
                            {
                                if (!Equals(relation.RELATION_ID, Relation_Id))
                                {
                                    isExist = true;
                                    break;
                                }
                            }
                            else
                            {
                                //Kiem tra truong hop them moi
                                isExist = true;
                                break;
                            }
                        }
                    }
                }
                if (isExist)
                {
                    return Json(Resources.Localization.RelationCodeExist);
                }
                else
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        private string GetFunction()
        {
            return "Danh mục mối quan hệ - RelationController";
        }
    }
}
